﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Windows;

namespace 智慧无纸化会议客户端软件
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : System.Windows.Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                Process currentProcess = Process.GetCurrentProcess();
                if (Process.GetProcessesByName(currentProcess.ProcessName).Length > 1)
                {
                    MessageBox.Show("应用程序已经在运行中...");
                    Environment.Exit(0);

                    return;
                }

                SetAutoRun();
            }
            catch (Exception ex)
            {
                Code.LoggerProxy.Exception("App", "OnStartup", ex);
            }

            base.OnStartup(e);
        }

        private void SetAutoRun()
        {
            try
            {
                string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

                string appName = System.IO.Path.GetFileName(appPath);

                using (Microsoft.Win32.RegistryKey local = Microsoft.Win32.Registry.CurrentUser)
                {
                    using (RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
                    {
                        if (key.GetValue(appName) == null) key.SetValue(appName, appPath);
                    }
                }
            }
            catch
            {
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            try
            {
                if (Code.EventAction.ExitAction != null) Code.EventAction.ExitAction();
                base.OnExit(e);
            }
            catch
            {
            }
        }
    }
}
